import code
from crypt import methods
from curses import meta, use_default_colors
from email import message
import imp
import re
from ssl import SSLSession
from tabnanny import check
from time import time
from tokenize import Exponent
from webbrowser import get
from zlib import DEF_BUF_SIZE
from flask import Flask, jsonify, request, session
from pip import main
from create_db import app,Admin,Users,Tips,Message,MessageToTips,db

# 实例化一个flaskApp

@app.route('/')
def hello():
    return 'Hello World'

# 管理员初始化
@app.route('/init/admin',methods=['POST'])
def init_admin():
        a = request.get_json()   #获取发送的数据
        new_username = a.get('username')
        new_password = a.get('password')
        # 检查参数是否完整
        if not all([new_username,new_password]):
            return jsonify(code=401,msg='缺少参数')
        # 向数据库内新增管理员用户
        admin =Admin(username = new_username,password = new_password)
        try:
            db.session.add(admin)
            db.session.commit()
            return jsonify(msg='新增成功！')
        except Exception as e:
            db.session.rollback()
            return jsonify(code=400,msg='出错拉！')

#管理员登录
@app.route('/admin',methods=['POST'])
def login_admin():
    req_data = request.get_json()
    username = req_data.get("username")
    password = req_data.get("password")
    # 检测传入信息是否完整
    if not all([username,password]):
        return jsonify(code=400,msg='请填写完整账号密码！')
    # 检查账号密码是否正确
    check = Admin.query.get(1)
    if username != check.username or password != check.password:
        return jsonify(code=400,msg="账号或密码错误！")
    # 正确即存储登陆信息到session
    session['admin_name'] = username
    session['admin_id'] = check.id
    return jsonify(code=200,msg='登陆成功！')

# 检测登陆状态
@app.route('/checkadmin/login',methods=['GET'])
def check_login_admin():
    check_admin_name = session.get('admin_name')
    # 逻辑：如果session内有信息即已登陆
    if check_admin_name is not None:
        return jsonify(code=200,msg='用户已登陆')
    else:
        return jsonify(code=400,msg='出错了！没登陆！')

# 管理员退出登录
@app.route('/admin/logout',methods=['GET'])
def admin_logout():
    # 清空session对象方法
    session.clear()
    return jsonify(msg="clear success!")

# 管理员新增标签
@app.route('/admin/addtips',methods=['POST'])
def admin_addtips():
    req_data = request.get_json()
    admin_id = session.get('admin_id')
    tip_name = req_data.get('tip_name')
    # 检查数据完整性
    if not all([admin_id,tip_name]):
        return jsonify(code=400,msg='出错或未登录！')

    # 向tips表内新增数据
    tip = Tips(admin_id=admin_id,content=tip_name)
    try:
        db.session.add(tip)
        db.session.commit()
        return jsonify(code=200,msg='新增标签成功！')
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify(msg='新增标签失败！')
# 管理员删除标签
@app.route('/admin/deltips',methods=['DELETE'])
def admin_deltips():
    req_data = request.get_json()
    admin_id = session.get('admin_id')
    tip_name = req_data.get('tip_name')
    # 检查数据完整性
    if not all([admin_id,tip_name]):
        return jsonify(code=400,msg='出错啦或未登录！')
    try:
        tip = Tips.query.filter(Tips.content == tip_name).delete()
        db.session.commit()
        return jsonify(code=200,msg='删除标签成功！')
    except Exception as e:
        return jsonify(msg='删除标签失败！')

#管理员删除留言
@app.route('/admin/delmessage',methods=['POST'])
def admin_delmessage():
    req_data = request.get_json()
    message_id =req_data.get('message_id')
    admin_id = session.get('admin_id')
    if not all([message_id,admin_id]):
        return jsonify(code=400,msg='出错啦！可能未登录！')
    # 判断留言是否存在
    msg = Message.query.get(id)
    if msg is None:
        return jsonify(code=200,msg='错误！留言不存在！')
    # 删除留言
    try:
        admin_del_message = Message.query.filter(Message.id == message_id).delete()
        db.session.commit()
        return jsonify(code=200,msg='删除成功！')
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify(msg='出错啦！')
    
# 用户注册
@app.route('/user/register',methods=['POST'])
def user_register():
    b = request.get_json()
    new_username = b.get('username')
    new_password = b.get('password')
    # 检查参数是否完整
    if not all([new_username,new_password]):
        return jsonify(code=401,msg='缺少参数')
    # 向数据库内新增用户
    user = Users(username = new_username,password = new_password)
    try:
        db.session.add(user)
        db.session.commit()
        return jsonify(code=200,msg='注册成功！')
    except Exception as e:
        db.session.rollback()
        return jsonify(code=400,msg='出错拉!请联系管理员')

# 用户登陆
@app.route('/user/login',methods=['POST'])
def user_login():
    req_data = request.get_json()
    get_username = req_data.get("username")
    get_password = req_data.get("password")
    # 检测参数是否完整
    if not all([get_username,get_password]):
        return jsonify(code=400,msg="请输入完整的账号密码！")
    check_user = Users.query.filter(Users.username == get_username).first()
    # 判断账号是否存在
    if check_user is None:
        return jsonify(msg='账号不存在！')
    # 判断账号密码是否错误
    elif get_username != check_user.username or get_password != check_user.password:
        return jsonify(msg='账号密码错误')
    # 如果正确，则存储信息到session中
    session['username'] = check_user.username
    session['user_id'] = check_user.id
    return jsonify(msg='登录成功！')

#检查用户是否登录
@app.route('/checkuser/login',methods=['GET'])
def check_user_login():
    check_username = session.get('username')
    check_user_id = session.get('user_id')
    if check_username is not None:
        return jsonify(user_id=check_user_id,username=check_username,msg='用户已登录！')
    else:
        return jsonify(msg='未登录！')

# 用户退出登录
@app.route('/user/logout',methods=['GET'])
def user_logout():
    session.clear()
    return jsonify(msg="clear success!")

# 用户发布留言
@app.route('/user/message',methods=['POST'])
def user_message():
    req_data = request.get_json()
    new_content = req_data.get('content')
    userid = session.get('user_id')
    if not all([new_content,userid]):
        return jsonify(code=400,msg='参数不完整！或未登录')
    try:
        message = Message(content = new_content,uesr_id = userid,)
        db.session.add(message)
        db.session.commit()
        return jsonify(code=200,msg='留言发布成功！')
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify(code=400,msg='留言发布失败，请联系管理员！')
#用户删除留言
@app.route('/user/delmessage',methods=['DELETE'])
def user_delmessage():
    req_data = request.get_json()
    message_id = req_data.get('message_id')
    user_id = session.get('user_id')
    if not all([message_id,user_id]):
        return jsonify(code=400,msg='参数错误或未登录！')
    
    # 判断留言是否存在
    msg = Message.query.get(id)
    if msg is None:
        return jsonify(code=400,msg='留言不存在！')
    # 判断是否为该用户的留言
    if user_id != msg.users.id:
        return jsonify(code=400,msg='您无权限')
    try:
        del_message = Message.query.filter(Message.id == message_id).delete()
        db.session.commit()
        return jsonify(code=200,msg='删除成功！')
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify(msg='出错啦！')
# 用户查看留言
@app.route('/user/look',methods=['GET'])
def user_look():
    # userid = session.get('user_id')
    # if userid is None :
    #     return jsonify(code=400,msg='出错啦！未登录！')
    # get_message = Message.uesr_id
    # all_content =[]
    # for message in get_message:
    #     time = message.creat_time.strftime('%Y-%m-%d %H:%i:%s')
    #     content = message.content
    #     data =  {'content':content,
    #             'time':time
    #             }
    #     all_content.append(data)
    # return jsonify(code=200,msg='查询成功！',data=all_content)
    return '未完成！'
    
if __name__ == '__main__':
    app.run()